package com.atxwq.shop.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atxwq.shop.model.entity.system.SysUser;
import com.atxwq.shop.model.vo.common.RedisCodeEnum;
import com.atxwq.shop.model.vo.common.Result;
import com.atxwq.shop.model.vo.common.ResultCodeEnum;
import com.atxwq.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Description 拦截器类
 * @Date 2025/5/8 20:38
 * @Created by 12336
 */

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String > redisTemplate;

    /**
     * 在请求处理之前执行，返回true表示继续执行，返回false表示拦截该请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求方式
        // 如果请求是options,预检请求，直接放行
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }
        //2.获取token
        String token = request.getHeader("token");

        //3.判断token是否为空
        if(StrUtil.isEmpty(token)){
            responseNoLoginInfo(response);//响应未登录信息
            return false;
        }

        //4.验证token合法性，redis查询不到返回错误信息
        String userInfoString = redisTemplate.opsForValue().get(RedisCodeEnum.USER_LOGIN_TOKEN + token);
        if(StrUtil.isEmpty(userInfoString)){
            responseNoLoginInfo(response);//响应未登录信息
            return false;
        }

        //5.验证通过，存入ThreadLocal中
        SysUser sysUser = JSON.parseObject(userInfoString, SysUser.class);
        AuthContextUtil.set(sysUser);

        //6.更新redis过期时间
        redisTemplate.expire(RedisCodeEnum.USER_LOGIN_TOKEN + token,30, TimeUnit.MINUTES);
        //7.放行
        return true;
    }

    //响应208状态码给前端,提示前端token无效
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    /**
     * 请求处理之后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除ThreadLocal数据
        AuthContextUtil.remove();
    }

}
